﻿#ifndef COMMON_H
#define COMMON_H

//平台相关函数定义
#if defined(_MSC_VER_) || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#include <io.h>
#include <Windows.h>
#include <direct.h>
#include <stdio.h>

#define SPRINTF                             sprintf_s
#define SSCANF                              sscanf_s
#define ACCESS                              _access
#define F_OK                                0
#define MKDIR                               _mkdir
#define RMDIR                               _rmdir
#define GETCWD                              _getcwd
#define CHDIR                               _chdir
#define LOAD_LIB(NAME)                      LoadLibraryExA(NAME, NULL, LOAD_WITH_ALTERED_SEARCH_PATH)
#define FIND_FUNC(PLIB, NAME)               GetProcAddress((HMODULE)PLIB, NAME)
#define CLOSE_LIB(PLIB)                     FreeLibrary((HMODULE)PLIB)
#define SHUT_RDWR                           SD_BOTH
#define MSG_NOSIGNAL                        0
#define _MM_REALLOC(PMEM, SIZE, ALIGNMENT) \
                                            _aligned_realloc(PMEM, SIZE, ALIGNMENT)
#else
#include <unistd.h>
#include <dlfcn.h>
#include <mm_malloc.h>
#include <malloc.h>
#include <sys/stat.h>

#define SPRINTF                             sprintf
#define SSCANF                              sscanf
#define ACCESS                              access
#define MKDIR(PDIR)                         mkdir(PDIR, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
#define RMDIR                               rmdir
#define GETCWD                              getcwd
#define CHDIR                               chdir
#define LOAD_LIB(NAME)                      dlopen(NAME, RTLD_NOW)
#define FIND_FUNC(PLIB, NAME)               dlsym(PLIB, NAME)
#define CLOSE_LIB(PLIB)                     dlclose(PLIB)
#define FIONBIO                             0
#define closesocket                         close
#define _MM_REALLOC(PMEM, SIZE, ALIGNMENT) \
                                            ({\
                                                int nOldSize = malloc_usable_size(PMEM);\
                                                void *pMem = PMEM;\
                                                if (nOldSize < (SIZE))\
                                                {\
                                                    pMem = _mm_malloc(SIZE, ALIGNMENT);\
                                                    memcpy(pMem, PMEM, nOldSize);\
                                                    _mm_free(PMEM);\
                                                }\
                                                pMem;\
                                            })
#endif

//功能宏定义
#define ALIGN128(SIZE)                      ((((SIZE) + 127) >> 7) << 7)
#define MAX2NUM(A, B)                       ((A) >= (B) ? (A) : (B))
#define MIN2NUM(A, B)                       ((A) <= (B) ? (A) : (B))

#endif // COMMON_H
